<template>
  <div class="w-full h-100vh flex justify-center items-center">
    <div class="login w-400px h-300px border">
      <h1 class="text-center text-3xl py-20px">邦邦物流管理系统</h1>
      <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名!' }]"
        >
          <a-input v-model:value="formState.username" />
        </a-form-item>

        <a-form-item
          label="密码"
          name="password"
          :rules="[{ required: true, message: '请输入密码!' }]"
        >
          <a-input-password v-model:value="formState.password" />
        </a-form-item>

        <a-form-item
          label="验证码"
          name="captcha"
          :rules="[{ required: true, message: '请输入验证码!' }]"
        >
          <a-input v-model:value="formState.captcha" />
          <img :src="verifyCode" alt="" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit">Submit</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { getVerifyCodeApi, loginApi } from '@/api/auth/index'
  import { LoginParams } from '@/api/auth/types'
  import { useAuthStore } from '@/store/auth'
  import { useRouter } from 'vue-router'

  // 请求验证码
  const verifyCode = ref('')
  const date = new Date().getTime().toString()
  getVerifyCodeApi(date).then((res: any) => {
    verifyCode.value = res.result
  })

  // 表单数据
  const formState = reactive<LoginParams>({
    username: 'admin',
    password: '123456',
    captcha: '', // 验证码
    checkKey: '', // 获取验证码时的时间戳
  })

  // 提交表单 表示 要请求登录接口
  const store = useAuthStore()

  const router = useRouter()

  const onFinish = () => {
    formState.checkKey = date
    console.log('Success:', formState)
    loginApi(formState).then((res) => {
      // 表示登录成功
      console.log(res)
      // 保存token
      store.setToken(res.result.token)
      store.setUserInfo(res.result.userInfo)

      // 跳转
      router.push({ path: '/dashboard/analysis' })
    })
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
</script>
